const fs = require('fs')
const path = require('path')

function camelize(str) {
	let camelizeRE = /-(\w)/g
	return str.replace(camelizeRE, function(_, c) {
		return c ? c.toUpperCase() : ''
	})
}

function isJsFile(fileName) {
	return /\.js$/.test(fileName)
}

let tabBar = {}

const createPageJson = function(config, routerPath = '../src/pages-config/') {
	let config2 = config || {}
	const srcPath = path.resolve(__dirname, routerPath)
	const result = fs.readdirSync(srcPath) || []

	result.forEach(v => {
		let nameArr = v.split('.')
		let name = camelize(nameArr[0])
		if (isJsFile(v)) {
			const route = require(routerPath + v)
			if (name === 'pages') return
			if (name === 'tabBar') {
				tabBar = route
				console.log('tabBar')
			} else if (Array.isArray(config2)) {
				config2.push(route)
			} else {
				config2[name] = route
			}
		} else if (camelize(v) === 'subPackages') {
			let arr = createPageJson([], routerPath + v + '/')

			let previewItem = arr.find(v => v.root === 'packages/preview-h5')
			if (previewItem) {
				let { pages, root } = previewItem
				let arr2 = []

				pages.forEach(v2 => {
					arr2.push({
						...v2,
						path: root + '/' + v2.path
					})
				})

				if (arr2.length) {
					config2['pages'] = arr2
				}
			}
		}
	})

	return config2
}

const configStr = JSON.stringify(createPageJson(), null, '  ') + '{{endjson}}'
const tabBarStr = !tabBar.list || tabBar.list.length < 2 ? '' : JSON.stringify(tabBar, null, '  ')

const strJson = configStr.replace(
	/(}{{endjson}})/g,
	tabBarStr ? '	 // #ifndef H5 \n ,\n "tabBar": ' + tabBarStr + ' \n /* #endif  */\n}' : '\n}'
)

fs.writeFile(path.resolve(__dirname, '../src/pages.json'), strJson, e =>
	e ? console.error(e) : console.log('pages.json 配置文件更新成功')
)
